package com.heima.kafka.test;

import org.apache.kafka.clients.consumer.*;
import org.apache.kafka.common.TopicPartition;

import java.time.Duration;
import java.util.Collections;
import java.util.Map;
import java.util.Properties;

/**
 * Author: Administrator
 * CreateTime: 2024/10/1
 * Project: heima-leadnews
 */
public class ConsumerQuickStart {
    public static void main(String[] args) {
        Properties properties = new Properties();
        // 1.设置kafka的配置信息
        // 连接信息
        properties.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, "10.118.1.171:9092");
        // 指定消费者组
        properties.put(ConsumerConfig.GROUP_ID_CONFIG, "group1");
        // 反序列化的key和value
        properties.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringDeserializer");
        properties.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringDeserializer");

        // 2.创建消费者对象
        KafkaConsumer<String, String> consumer = new KafkaConsumer<>(properties);

        // 3.订阅主题
        consumer.subscribe(Collections.singletonList("topic"));

        // 4.获取消息
        // 同步提交
//        while (true) {
//            ConsumerRecords<String, String> records = consumer.poll(Duration.ofMillis(1000));
//            for (ConsumerRecord<String, String> record : records) {
//                System.out.println(record.value());
//                System.out.println(record.key());
//                try {
//                    consumer.commitSync(); // 同步提交当前最新的偏移量
//                } catch (CommitFailedException e) {
//                    System.out.println("记录提交失败的异常：" + e);
//                }
//            }
//        }
        // 异步提交
//        while(true) {
//            ConsumerRecords<String, String> records = consumer.poll(Duration.ofMillis(1000));
//            for (ConsumerRecord<String, String> record : records) {
//                System.out.println(record.value());
//                System.out.println(record.key());
//            }
//            consumer.commitAsync((map, e) -> {
//                if (e != null) System.out.println("记录提交失败的异常：" + e);
//                System.out.println("异步提交成功");
//            });
//            System.out.println("程序仍然在执行");
//        }
        // 异步同步组合
        try {
            while(true){
                ConsumerRecords<String, String> records = consumer.poll(Duration.ofMillis(1000));
                for (ConsumerRecord<String, String> record : records) {
                    System.out.println(record.value());
                    System.out.println(record.key());
                }
                consumer.commitAsync();
            }
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("程序出现异常，准备退出");
        } finally {
            try {
                consumer.commitSync();
            } finally {
                consumer.close();
            }
        }
    }
}
